package dao.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import model.AsistentSocial;
import model.Sponsor;
import dao.DaoException;
import dao.SponsorDao;

public class SponsorDaoImpl extends Dao implements SponsorDao {

	@Override
	public void addOrUpdateSponsor(Sponsor sponsor) {
		hibernateTemplate.saveOrUpdate(sponsor);
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public Set<Sponsor> getAllSponsori() {
		List<Sponsor> res= hibernateTemplate.loadAll(Sponsor.class);
		return new HashSet<Sponsor>(res);
	}

	@Override
	public void removeSponsor(int id) throws DaoException {
		hibernateTemplate.delete(this.getSponsorByID(id));
		
	}

	@Override
	public Sponsor getSponsorByID(int id) throws DaoException {
		DetachedCriteria crit = DetachedCriteria.forClass(Sponsor.class).add(Restrictions.eq("id", id));
        @SuppressWarnings("rawtypes")
		List res = hibernateTemplate.findByCriteria(crit);
        if (res.size() == 0) {
            throw new DaoException("Nu s-a gasit nici un sponsor cu acest id");
        }
       
        return (Sponsor) res.get(0);
	}

	@Override
	public int getMaxId() {
		List res= hibernateTemplate.find("select max(sponsorId) from Sponsor");
		if( res.get(0) == null || res.isEmpty() ) return 0;
		return Integer.parseInt(res.get(0).toString());
	}

}
